package controller;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zxf.pojo.Article;
import com.zxf.pojo.BootStrapPage;
import com.zxf.pojo.Content;
import com.zxf.pojo.Params;
import com.zxf.pojo.Users;
import com.zxf.service.ArticleService;
import com.zxf.service.UserService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import util.DateJsonValueProcessor;

@Controller
@RequestMapping("/indexs")
public class IndexsController {

	@Autowired
	private ArticleService articleService;
	
	@Autowired
	private UserService userService;

	private static Logger logger = Logger.getLogger(IndexsController.class);
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	public String login() {
		return "login";
	}

	// 文章列表
	@RequestMapping(value = "/index.do")
	public @ResponseBody
	ModelAndView index(Params params, String author, String title,
			String source, String articleID, String startime, String endtime,
			Article article, HttpServletRequest request,
			HttpServletResponse response) {
		String contents = request.getParameter("content");

		System.out.println("start 水电费水电费 invoked...");
		JSONObject obj = new JSONObject();

		try {
			if (null != startime && !"".equals(startime)) {
				params.setStartdate(sdf.parse(startime));
			}
			if (null != endtime && !"".equals(endtime)) {
				params.setEnddate(sdf.parse(endtime));
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		JSONArray js = new JSONArray();
		// 页码
		params.setPage(1);
		params.setLimit(10);
		int pageno = params.getPage();
		// 每页数量
		int pageSize2 = params.getLimit();
		// int start2 = (Integer.parseInt(pageno)-1)*Integer.parseInt(pageSize);
		int start = (params.getPage() - 1) * params.getLimit();
		params.setStart(start);
		JsonConfig jsonConfig = new JsonConfig();
		// 实体类里面存在的时间类型为Timestamp,之前放的Date,解析格式还是原来那样,后来换成这个好使。
		// jsonConfig.registerJsonValueProcessor(Date.class, new
		// JsonDateValueProcessor());
		int typeid = 0;
		String key = "zxfzxc2d5a106f5-6f5e-4770-8191-7da735df0784";
		
		Users user = userService.getUser(key);
		List articlelist1 = articleService.getArticleList(1, 10);
		List articlelist2 = articleService.getArticleList(2, 10);
		List articlelist3 = articleService.getArticleList(3, 10);
		List articlelist4 = articleService.getArticleList(4, 10);
		int totle = articleService.getartcletotle(params, article);

		System.out.println(obj.toString());

		ModelAndView modelAndView = new ModelAndView("webshow/index/index");
		modelAndView.addObject("articlelist1", articlelist1);
		modelAndView.addObject("articlelist2", articlelist2);
		modelAndView.addObject("articlelist3", articlelist3);
		modelAndView.addObject("articlelist4", articlelist4);
		modelAndView.addObject("user", user);
		modelAndView.addObject("totle", totle);
		return modelAndView;

	}

	@RequestMapping(value = "/xzlogin.do")
	public String xzLogin(HttpServletRequest request,
			HttpServletResponse response) {

		System.out.println("start 水电费水电费 invoked...");

		return "index";

	}

	// 用户登录
	@RequestMapping("/userlogin")
	public @ResponseBody
	JSONObject userlogin(Users users, HttpServletRequest request,
			HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		HttpSession session = request.getSession();
		// StringBuffer toJson=new StringBuffer();//用来放json数据
		JSONArray js = new JSONArray();
		Users users2 = new Users();
		// 得到生成的验证码
		String strCode = (String) session.getAttribute("randomCode");
		System.out.println("UserAction>randomCode:" + strCode);
		// 定义一个msg变量,可用于存放错误信息,然后传到前台
		// 用于告诉前台时候登录成功
		boolean successe = false;
		if (!users.getCheckCode().toLowerCase().equals(strCode.toLowerCase())) {
			obj.put("success", false);
			obj.put("message", "验证码错误！");
			return obj;

		}

		// users2 = userService.selectusers(users);

		if (null != users2) {
			obj.put("users", users2);
			obj.put("success", true);

		} else {
			obj.put("success", false);
			obj.put("message", "用户名或者密码错误！");

		}

		// response.setHeader("Cache-Control", "no-cache");
		// response.setContentType("text/json;charset=utf-8");
		// response.getWriter().write(obj.toString());
		// TODO Auto-generated catch block
		// json格式化后输出
		System.out.println(obj.toString());
		return obj;

	}

	// 查看
	@ResponseBody
	@RequestMapping(value = "/detailarticle.do")
	public ModelAndView detailarticle(String articleID, String title,
			HttpServletRequest request, HttpServletResponse response) {
		int artid = 0;
		Article previousarticle = new Article();
		Article article = new Article();
		Article nextarticle = new Article();
		Content content = new Content();
		
		try {
			title =new String(title.getBytes("iso-8859-1"),"utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		if (null != articleID && !"".equals(articleID))
			artid = Integer.parseInt(articleID);
		
		
		
		//取的文章信息
		article = articleService.detailarticle(artid);
		//文章类别
		int typeid = article.getChannelid();
		previousarticle = articleService.findPrevious(artid,typeid);
		nextarticle = articleService.findNextarticle(artid,typeid);
		content = articleService.detailcontent(title);
		if (null != content) {
			article.setContent(content.getContent());
			article.setContentid(content.getArticleid());
		}
		ModelAndView modelAndView = new ModelAndView("webshow/index/detailarticle");
		modelAndView.addObject("previousarticle", previousarticle);
		modelAndView.addObject("article", article);
		modelAndView.addObject("nextarticle", nextarticle);
		

		return modelAndView;
	}
	// 文章列表
		@RequestMapping(value = "/articlelist.do", method=RequestMethod.POST)
		public @ResponseBody JSONObject userlist(Params params,BootStrapPage temp, String author, String searchText,
				String source, String articleID, String typeid, String startime,String limit,String offset, 
				String endtime,String channelid, Article article, HttpServletRequest request,
				HttpServletResponse response) {
			JSONObject obj = new JSONObject();
			//String temp= (String) request.getParameter("temp");
			int limits=0;
			int start = 0;
			int channelID =0;
			if(null != limit && limit != "")
				limits = Integer.parseInt(limit);
			if(null != offset && offset != ""&& offset!="0")
				start = Integer.parseInt(offset);
			if(null != channelid && channelid != ""){
				channelID = Integer.parseInt(channelid);
				article.setChannelid(channelID);
				
			}
				
			try {
				if (null != startime && !"".equals(startime)) {
					params.setStartdate(sdf.parse(startime));
				}
				if (null != endtime && !"".equals(endtime)) {
					params.setEnddate(sdf.parse(endtime));
				}
				
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			JSONArray js = new JSONArray();
			params.setLimit(limits);
			// 页码
			int pageno = params.getPage();
			// 每页数量
			int pageSize2 = params.getLimit();
			// int start2 = (Integer.parseInt(pageno)-1)*Integer.parseInt(pageSize);
			params.setStart(start);
			JsonConfig jsonConfig = new JsonConfig();
			// 实体类里面存在的时间类型为Timestamp，之前放的Date，解析格式还是原来那样，后来换成这个好使。
			// jsonConfig.registerJsonValueProcessor(Date.class, new
			// JsonDateValueProcessor());
			jsonConfig.registerJsonValueProcessor(java.sql.Timestamp.class,
					new DateJsonValueProcessor("yyyy-MM-dd"));
			List articlelist = articleService.getArticleList(params, article);
			int totle = articleService.getartcletotle(params, article);
			obj.put("total", totle); // 统计数量，这里写死10条
			obj.put("rows", js.fromObject(articlelist, jsonConfig));
			
			obj.put("success", true);

			// /response.setHeader("Cache-Control", "no-cache");
			// response.setContentType("text/json;charset=utf-8");
			// response.getWriter().write(obj.toString());
			// TODO Auto-generated catch block
			// json格式化后输出
			System.out.println(obj.toString());
			return obj;

		}
		@RequestMapping(value = "/getarticlelist.do")
		public @ResponseBody
		ModelAndView getarticlelist(Params params, String author, String title,
				String source, String articleID, String startime, String endtime,
				Article article, HttpServletRequest request,
				HttpServletResponse response) {
			String contents = request.getParameter("content");

			System.out.println("start 水电费水电费 invoked...");
			JSONObject obj = new JSONObject();

			try {
				if (null != startime && !"".equals(startime)) {
					params.setStartdate(sdf.parse(startime));
				}
				if (null != endtime && !"".equals(endtime)) {
					params.setEnddate(sdf.parse(endtime));
				}
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			JSONArray js = new JSONArray();
			// 页码
			params.setPage(1);
			params.setLimit(10);
			int pageno = params.getPage();
			// 每页数量
			int pageSize2 = params.getLimit();
			// int start2 = (Integer.parseInt(pageno)-1)*Integer.parseInt(pageSize);
			int start = (params.getPage() - 1) * params.getLimit();
			params.setStart(start);
			JsonConfig jsonConfig = new JsonConfig();
			// 实体类里面存在的时间类型为Timestamp,之前放的Date,解析格式还是原来那样,后来换成这个好使。
			// jsonConfig.registerJsonValueProcessor(Date.class, new
			// JsonDateValueProcessor());
			int typeid = 0;
			List articlelist1 = articleService.getArticleList(1, 10);
			List articlelist2 = articleService.getArticleList(2, 10);
			List articlelist3 = articleService.getArticleList(3, 10);
			List articlelist4 = articleService.getArticleList(4, 10);
			int totle = articleService.getartcletotle(params, article);

			
			ModelAndView modelAndView = new ModelAndView("webshow/index");
			modelAndView.addObject("articlelist1",articlelist1);
			modelAndView.addObject("articlelist2",articlelist2);
			modelAndView.addObject("articlelist3",articlelist3);
			modelAndView.addObject("articlelist4",articlelist4);
			
			return modelAndView;

		}
	
		@RequestMapping(value={"/userlist"})
		public @ResponseBody JSONObject userlist(Params params, BootStrapPage temp, String limit , String start,Users users,HttpServletRequest request, HttpServletResponse response) {
		 JSONObject obj = new JSONObject();
		// StringBuffer toJson=new StringBuffer();//用来放json数据 
		 JSONArray js = new JSONArray();
		 JsonConfig jsonConfig = new JsonConfig();
		
		//每页数量
		 int pageSize2 = 0;
		 if(null!=limit && limit!=""){
			 pageSize2 = Integer.parseInt(limit);
			 
		 }
		
	List userlist =  userService.getRedisUserList(params.getPage(),pageSize2);
	int totle = userService.getRedistotle("users");
	//System.out.println(pageno==1?pageno:(pageno-1));
	obj.put("total", totle); // 统计数量，这里写死10条
	obj.put("rows", js.fromObject(userlist, jsonConfig));
	 obj.put("success", true);
		
			// response.setHeader("Cache-Control", "no-cache");
			// response.setContentType("text/json;charset=utf-8"); 
			//response.getWriter().write(obj.toString());
			// TODO Auto-generated catch block
		//json格式化后输出
		 System.out.println(obj.toString());
				return obj;
			
		
    }
}
